﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Urs.Core;
using Urs.Core.Caching;
using Urs.Data.Domain.Stores;
using Urs.Data.Domain.Common;
using Urs.Data.Domain.Users;
using Urs.Data.Domain.Media;
using Urs.Data.Domain.Configuration;
using Plugin.Api.Models.Catalog;
using Plugin.Api.Models.Media;
using Plugin.Api.Models.Goods;
using Urs.Services.Stores;
using Urs.Services.Common;
using Urs.Services.Users;
using Urs.Services.Localization;
using Urs.Services.Media;
using Urs.Services.Security;
using Urs.Framework;
using Urs.Framework.Controllers;

namespace Plugin.Api.Controllers
{
    /// <summary>
    /// 品牌制造商接口
    /// </summary>
    [ApiVersion("1.0")]
    [Route("api/v{version:apiVersion}/brand")]
    [ApiController]
    public class BrandController : BaseApiController
    {
        private readonly ILocalizationService _localizationService;
        private readonly UserSettings _userSettings;
        private readonly StoreSettings _storeSettings;
        private readonly MediaSettings _mediaSettings;
        private readonly IPermissionService _permissionService;
        private readonly IUserService _userService;
        private readonly IBrandService _brandService;
        private readonly IPictureService _pictureService;
        private readonly IWebHelper _webHelper;
        private readonly ICacheManager _cacheManager;
        private readonly IGoodsService _goodsService;
        private readonly IGoodsParameterService _goodsParameterService;
        /// <summary>
        /// 构造器
        /// </summary>
        public BrandController(ILocalizationService localizationService,
            UserSettings userSettings,
            StoreSettings storeSettings,
            MediaSettings mediaSettings,
            IPermissionService permissionService,
            IUserService userService,
            IBrandService brandService,
            IPictureService pictureService,
            IWebHelper webHelper,
            ICacheManager cacheManager,
            IGoodsService goodsService,
            IGoodsParameterService goodsParameterService)
        {
            this._localizationService = localizationService;
            this._userSettings = userSettings;
            this._storeSettings = storeSettings;
            this._mediaSettings = mediaSettings;
            this._permissionService = permissionService;
            this._userService = userService;
            this._brandService = brandService;
            this._pictureService = pictureService;
            this._webHelper = webHelper;
            this._cacheManager = cacheManager;
            this._goodsService = goodsService;
            this._goodsParameterService = goodsParameterService;
        }

        #region Utilities
        [NonAction]
        protected IEnumerable<MoGoodsOverview> PrepareGoodsOverviewModels(IEnumerable<Goods> list,
            bool preparePriceModel = true, bool preparePictureModel = true,
            int? goodsThumbPictureSize = null, bool prepareGoodsParameters = false, bool prepareGoodsTag = false,
            bool forceRedirectionAfterAddingToCart = false, bool prepareFullDescription = false)
        {
            if (list == null)
                throw new ArgumentNullException("list");

            var models = new List<MoGoodsOverview>();
            foreach (var goods in list)
            {
                var model = new MoGoodsOverview()
                {
                    Id = goods.Id,
                    Sku = goods.Sku,
                    Name = goods.Name,
                    Short = goods.ShortDescription,
                    Qty = goods.StockQuantity,
                    SaleVolume = goods.SaleVolume
                };
                //price
                if (preparePriceModel)
                {
                    #region Prepare goods price

                    var priceModel = new MoGoodsOverview.MoPrice();
                    priceModel.OldPrice = PriceFormatter.FormatPrice(goods.OldPrice);
                    priceModel.Price = PriceFormatter.FormatPrice(goods.Price);
                    model.Price = priceModel;
                    #endregion
                }

                if (prepareFullDescription)
                {
                    model.Full = goods.FullDescription;
                }

                //picture
                if (preparePictureModel)
                {
                    #region Prepare goods picture

                    //If a size has been set in the view, we use it in priority
                    int pictureSize = goodsThumbPictureSize.HasValue ? goodsThumbPictureSize.Value : _mediaSettings.GoodsThumbPictureSize;
                   
                        var picture = goods.GetDefaultGoodsPicture(_pictureService);
                        var pictureModel = new MoPicture()
                        {
                            NormalUrl = _pictureService.GetPictureUrl(picture, pictureSize),
                            BigUrl = _pictureService.GetPictureUrl(picture)
                        };
                        model.Picture =pictureModel;
                   
                    #endregion
                }

                if (prepareGoodsTag)
                {
                    for (int i = 0; i < goods.GoodsTags.Count; i++)
                    {
                        var pt = goods.GoodsTags.ToList()[i];
                        model.Tags.Add(new MoGoodsOverview.MoGoodsTag()
                        {
                            Id = pt.GoodsTag.Id,
                            Name = pt.GoodsTag.Name
                        });
                    }
                }

                //specs
                if (prepareGoodsParameters)
                {
                    //specs for comparing
                    model.Specs = PrepareGoodsSpecificationModel(goods);
                }
                models.Add(model);
            }
            return models;
        }
        [NonAction]
        protected IList<MoSpecification> PrepareGoodsSpecificationModel(Goods goods)
        {
            if (goods == null)
                throw new ArgumentNullException("goods");

                var model = _goodsParameterService.GetGoodsParameterMappingByGoodsId(goods.Id, null, true)
                   .Select(psa =>
                   {
                       return new MoSpecification()
                       {
                           Name = psa.GoodsParameterOption.Mapping.Name,
                           Value = !String.IsNullOrEmpty(psa.CustomValue) ? psa.CustomValue : psa.GoodsParameterOption.Name,
                       };
                   }).ToList();
                return model;
        }
        [NonAction]
        protected MoSimpleBrand PrepareBrandModel(Brand brand, bool preparePictureModel = true, int? mfrPictureSize = null)
        {
            var model = new MoSimpleBrand()
            {
                Id = brand.Id,
                Name = brand.Name,
                Desc = brand.Description,
            };
            //picture
            if (preparePictureModel || mfrPictureSize.HasValue)
            {
                #region Prepare brand picture

                //If a size has been set in the view, we use it in priority
                int pictureSize = mfrPictureSize ?? _mediaSettings.BrandThumbPictureSize;
                    var picture = _pictureService.GetPictureById(brand.PictureId);
                    var pictureModel = new MoPicture()
                    {
                        NormalUrl = _pictureService.GetPictureUrl(picture, pictureSize),
                        BigUrl = _pictureService.GetPictureUrl(picture)
                    };
                    model.Picture = pictureModel;
                
                #endregion
            }

            return model;
        }
        #endregion

        /// <summary>
        /// 获取品牌列表
        /// </summary>
        /// <param name="name">品牌名称(默认:0)</param>
        /// <param name="picsize">图片大小px (默认:空)</param>
        /// <param name="page">页码（默认:1）</param>
        /// <param name="size">页大小（默认值:12）</param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<ApiResponse<MoBrandList>> List(string name = "", int? picsize = null, int page = 1, int size = 12)
        {
            var data = await Task.Run(() =>
             {
                 var command = new PagingFiltering
                 {
                     PageNumber = page,
                     PageSize = size > 0 ? size : 10
                 };

                 var brands = _brandService.GetAll(name, command.PageIndex, command.PageSize);

                 var list = new MoBrandList();
                 list.Items = brands.Select(m => PrepareBrandModel(m, false, picsize)).ToList();
                 list.Paging.Page = page;
                 list.Paging.Size = size;
                 list.Paging.TotalPage = brands.TotalPages;

                 return list;
             });

            return ApiResponse<MoBrandList>.Success(data);
        }

        /// <summary>
        /// 获取推荐的品牌列表
        /// </summary>
        /// <param name="picsize">图片大小(px)(非必填)</param>
        /// <returns></returns>
        [HttpGet("featurelist")]
        public async Task<ApiResponse<List<MoSimpleBrand>>> FeaturedList(int? picsize = null)
        {
            var data = await Task.Run(() =>
            {
                var brands = _brandService.ShowOnPublicPage();

                return brands.Select(m => PrepareBrandModel(m, false, picsize)).ToList();
            });
            return ApiResponse<List<MoSimpleBrand>>.Success(data);
        }

        /// <summary>
        /// 获取单个品牌制信息
        /// </summary>
        /// <param name="mid">品牌制造商Id</param>
        /// <param name="picsize">图片大小px (默认:空)</param>
        /// <returns></returns>
        [HttpGet("get")]
        public async Task<ApiResponse<MoSimpleBrand>> Get(int mid, int? picsize = null)
        {
            var mfr = _brandService.GetById(mid);
            if (mfr == null || mfr.Deleted || !mfr.Published)
                return ApiResponse<MoSimpleBrand>.BadRequest();

            var model = PrepareBrandModel(mfr, true, picsize);

            return ApiResponse<MoSimpleBrand>.Success(model);
        }
        /// <summary>
        /// 获取品牌的推荐商品
        /// </summary>
        /// <param name="mid">品牌Id</param>
        /// <param name="count">商品数量</param>
        /// <param name="specshow">显示参数</param>
        /// <param name="tagshow">显示标签</param>
        /// <param name="fullshow">显示内容</param>
        /// <returns></returns>
        [HttpGet("featuredgoods")]
        public async Task<ApiResponse<List<MoGoodsOverview>>> FeaturedGoods(int mid, int count,
             bool specshow = false, bool tagshow = false, bool fullshow = false)
        {
            var data = await Task.Run(() =>
              {
                  var list = new List<MoGoodsOverview>();
                  if (_brandService.GetTotalNumberOfFeaturedGoodss(mid) > 0)
                  {
                      var flist = _brandService.GetFeaturedGoodss(mid, count);
                      list = PrepareGoodsOverviewModels(flist,
                      prepareGoodsParameters: specshow, prepareGoodsTag: tagshow, prepareFullDescription: fullshow).ToList();
                  }
                  return list;
              });
            return ApiResponse<List<MoGoodsOverview>>.Success(data);
        }
    }
}
